package com.lg.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.lg.cms.dto.PermissionDTO;
import com.lg.cms.entity.Permission;
import com.lg.cms.entity.Role;
import com.lg.cms.entity.RolePermission;
import com.lg.cms.mapper.PermissionMapper;
import com.lg.cms.mapper.RoleMapper;
import com.lg.cms.mapper.RolePermissionMapper;
import com.lg.cms.service.PermissionService;
import com.lg.cms.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lg.cms.vo.admin.PermissionVO;
import org.apache.shiro.authz.permission.RolePermissionResolverAware;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author lg
 * @since 2020-09-21
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    RolePermissionMapper rolePermissionMapper;
    @Autowired
    PermissionMapper permissionMapper;

    /**
     * 批量删除角色, 并且删除当前角色所有权限
     *
     * @param roleIdArray
     * @return
     */
    @Override
    @Transactional //使用事务回滚机制保证数据一致性
    public R<?> deleteRolePermission(int[] roleIdArray) {
        try {
            for (int roleId : roleIdArray) {
                List<Integer> rolePermIdList = new ArrayList<>();
                rolePermissionMapper.selectList
                        (new QueryWrapper<RolePermission>().eq("role_id", roleId))
                        .forEach(v -> rolePermIdList.add(v.getId()));
                int result = 0;
                if(rolePermIdList.size() > 0){
                    result = rolePermissionMapper.deleteBatchIds(rolePermIdList);
                }
//                if (result != rolePermIdList.size()) {
//                    throw new Exception("删除权限时出错");
//                }
                result = roleMapper.deleteById(roleId);
//                if (result != 1) {
//                    throw new Exception("删除角色时出错");
//                }
            }
            return R.ok(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.failed(e.getMessage());
        }
    }


    /**
     * 设置, 更新角色权限
     * @param roleId
     * @param permissionIdArray
     * @return
     */
    @Transactional
    @Override
    public R<?> updatePermissionByRoleId(Integer roleId, int[] permissionIdArray) {
        Role role = roleMapper.selectById(roleId);
        Set<Integer> permissionIdSet = new HashSet<>();
        for(int i: permissionIdArray){
            permissionIdSet.add(i);
        }
        if(role == null){
            return R.failed("角色不存在");
        }
//        System.out.println("roleId:" + roleId);
//        System.out.println("permSet:");
//        permissionIdSet.forEach(System.out::println);
        try{
            rolePermissionMapper.delete(new QueryWrapper<RolePermission>().eq("role_id", roleId));
            for(int permissionId: permissionIdArray){
                Permission pTemp = permissionMapper.selectById(permissionId);
                if(pTemp.getUrl() == null){
                    continue;
                }
                RolePermission temp = new RolePermission();
                temp.setRoleId(roleId);
                temp.setPermId(permissionId);
                rolePermissionMapper.insert(temp);
            }
            return R.ok(null);
        }catch (Exception e){
            return R.failed(e.getMessage());
        }
    }
    /**
     * 获取角色权限权限列表
     * @return
     * 权限树结构
     * 带有角色是否有此权限的标识
     * 有标识就选中
     */
    @Override
    public List<PermissionVO> listPermissionByRoleId(Integer roleId) {
        //获取角色权限id列表
        Set<Integer> rolePermissionIdList = new HashSet<>();
        List<PermissionVO> permissionDTOList = new ArrayList<>();
        rolePermissionMapper.selectList
                (new QueryWrapper<RolePermission>().eq("role_id", roleId))
                .forEach(v -> rolePermissionIdList.add(v.getPermId()));
        //获取权限列表
        //获取父权限列表,三层数结构
        List<Permission> permissionList = permissionMapper.selectList(new QueryWrapper<Permission>().isNull("parent_id"));
        for(Permission fu: permissionList){
            PermissionVO temp = ToPermissionVO(fu, rolePermissionIdList.contains(fu.getId()));
            List<PermissionVO> fuList = new ArrayList<>();
            for(Permission zi: permissionMapper.selectList(new QueryWrapper<Permission>().eq("parent_id", fu.getId()))){
                PermissionVO tempZi = ToPermissionVO(zi,rolePermissionIdList.contains(zi.getId()));
                List<PermissionVO> ziList = new ArrayList<>();
                for(Permission sun: permissionMapper.selectList(new QueryWrapper<Permission>().eq("parent_id", zi.getId()))){
                    PermissionVO tempSun = ToPermissionVO(sun, rolePermissionIdList.contains(sun.getId()));
                    ziList.add(tempSun);
                }
                tempZi.setChildren(ziList);
                fuList.add(tempZi);
            }
            temp.setChildren(fuList);
            permissionDTOList.add(temp);
        }
        //做成树结构
        return permissionDTOList;
    }



    /**
     * permission对象转permissionDTO对象
     * @param permission
     * @return
     */
    private PermissionVO ToPermissionVO(Permission permission, Boolean use){
        PermissionVO vo = new PermissionVO();
        vo.setChecked(use);
        vo.setPermissionUrl(permission.getUrl());
        vo.setPermissionId(permission.getId());
        vo.setPermissionPerm(permission.getPerm());
        vo.setPermissionName(permission.getName());
        vo.setTitle(permission.getName());
        vo.setId(vo.getPermissionId());
        vo.setSpread(true);
        return vo;
    }


}
